<template>
  <div class="TemplateAdmin">
    <a-card>
      <a-form :form="form">
        <a-row :gutter="30">
          <a-col :span="8">
            <a-form-item label="商品编号" :label-col="{ span: 5}" :wrapper-col="{ span: 16, offset: 1}">
              <a-input placeholder="请输入" v-decorator="['goodsNumber']" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="模板名称" :label-col="{ span: 5}" :wrapper-col="{ span: 16, offset: 1}">
              <a-input placeholder="请输入" v-decorator="['templateName']" />
            </a-form-item>
          </a-col>
          <a-col :span="8" :style="{ textAlign: 'right' }">
            <a-button
              type="primary"
              @click="findPageListByCondition()"
              :style="{ marginRight: '1%' }"
            >查询</a-button>
            <a-button type="dashed" @click="listExport()" :style="{ marginRight: '1%' }">导出</a-button>
            <router-link to="/home/goodsadmin/templateadmin/templateadd">
              <a-button style="background:rgb(0,204,102);color:white;margin-left:2%">新增</a-button>
            </router-link>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card style="margin-top:2%">
      <a-table
        style="margin-top:2%"
        :columns="columns"
        :dataSource="data"
        :pagination="pagination"
        @change="handleTableChange"
        :rowKey="record => record.id"
        :bordered="true"
      >
        <template slot="bindingNumber" slot-scope="text,record">
          <span
            :class="record.deviceNumber==0?'':'blue'"
            @click="record.deviceNumber==0?'':numberModal(text,record)"
          >{{record.deviceNumber}}</span>
        </template>

        <template slot="templateGoods" slot-scope="text,record">
          <span class="blue" @click="goodsModal(text,record)">查看</span>
        </template>
        <template slot="operate" slot-scope="text,record">
          <span class="blue" @click="editInfo(text,record)">编辑</span>
          <span class="blue" @click="copyConfirm(text,record)">复制</span>
          <span
            class="red"
            @click="record.deviceNumber==0?delConfirm(text,record):deviceNumberConfirm(text,record)"
          >删除</span>
        </template>
      </a-table>
    </a-card>
    <a-modal
      title="编辑商品分类"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      v-model="visible"
    >
      <template slot="footer">
        <a-button key="back" @click="handleCancel">取消</a-button>
        <a-button key="submit" type="primary" @click="handleOk">确定</a-button>
      </template>
      <a-form :form="form">
        <a-form-item label="分类名称" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
          <a-input
            style="width: 100%"
            placeholder="请输入"
            v-decorator="[
          'classifyName',
          {rules: [{ required: true, message: '请输入分类名称!' }]} 
        ]"
          />
        </a-form-item>
        <a-form-item
          label="上级分类"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
          v-show="isSelect"
        >
          <a-select
            @select="select"
            @change="handleChange"
            @dropdownVisibleChange="dropdownVisibleChange"
            style="width: 100%"
            v-decorator="[
          'superiorClassify',
          {rules: [{ required: true, message: '请选择上级分类!' }]}
        ]"
            placeholder="请设置商品品牌"
          >
            <a-select-option
              v-for="item in selectdata"
              :key="item.id"
              :value="item.name"
            >{{item.name}}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal
      :title="numberTitle"
      :visible="numberVisible"
      @ok="numberOk"
      @cancel="numberCancel"
      :footer="null"
    >
      <a-table
        style="margin-top:2%"
        :columns="columnsNumber"
        :dataSource="dataNumber"
        :pagination="false"
        :rowKey="record => record.id"
        :bordered="true"
      >
        <template slot="number" slot-scope="text,record,index">
          <span>{{index+1}}</span>
        </template>
      </a-table>
    </a-modal>
    <a-modal
      :title="goodsTitle"
      :visible="goodsVisible"
      @ok="goodsOk"
      @cancel="goodsCancel"
      :footer="null"
    >
      <a-table
        style="margin-top:2%"
        :columns="columnsGoods"
        :dataSource="dataGoods"
        :pagination="false"
        :rowKey="record => record.code"
        :bordered="true"
      >
        <template slot="number" slot-scope="text,record,index">
          <span>{{index+1}}</span>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script>
const columns = [
  {
    title: "模板编号",
    dataIndex: "templateCode",
    key: "templateNumer",
    scopedSlots: { customRender: "templateNumer" },
    align: "center"
  },

  {
    title: "模板名称",
    dataIndex: "name",
    key: "templateName",
    scopedSlots: { customRender: "templateName" },
    align: "center"
  },
  {
    title: "绑定设备数",
    dataIndex: "deviceNumber",
    // key: "bindingNumber",
    scopedSlots: { customRender: "bindingNumber" },
    align: "center"
  },
  {
    title: "模板商品",
    dataIndex: "templateGoods",
    key: "templateGoods",
    scopedSlots: { customRender: "templateGoods" },
    align: "center"
  },
  {
    title: "操作",
    dataIndex: "",
    key: "operate",
    scopedSlots: { customRender: "operate" },
    align: "center"
  }
];

const columnsNumber = [
  {
    title: "序号",
    dataIndex: "number",
    key: "number",
    scopedSlots: { customRender: "number" },
    align: "center"
  },

  {
    title: "设备编号",
    dataIndex: "devCode",
    key: "facilityNumber",
    scopedSlots: { customRender: "facilityNumber" },
    align: "center"
  }
];

const columnsGoods = [
  {
    title: "序号",
    dataIndex: "number",
    key: "number",
    scopedSlots: { customRender: "number" },
    align: "center"
  },
  {
    title: "商品ID",
    dataIndex: "code",
    key: "goodsID",
    scopedSlots: { customRender: "goodsID" },
    align: "center"
  },
  {
    title: "商品名称",
    dataIndex: "name",
    key: "goodsName",
    scopedSlots: { customRender: "goodsName" },
    align: "center"
  }
];

const data = [
  {
    key: 1
  }
];

const dataNumber = [
  {
    key: 1
  }
];

const dataGoods = [
  {
    key: 1
  }
];
export default {
  name: "TemplateAdmin",
  data() {
    return {
      form: this.$form.createForm(this),
      data: [],
      columns,
      columnsNumber,
      dataNumber: [],
      columnsGoods,
      dataGoods: [],
      goodsVisible: false,
      numberVisible: false,
      pagination: {
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ["10", "20", "30", "40"], //每页条数选择器
        showTotal: (total, range) => {
          return `${range[0]}-${range[1]} 共${total}条`;
        }, // 总数展示
        pageSize: 10, //每页条数
        defaultCurrent: 1, //默认当前页
        current: 1, //当前页
        total: 50 //数据总条数
      },
      visible: false,
      selectdata: [],
      isSelect: false,
      numberTitle: "",
      goodsTitle: ""
    };
  },
  watch: {},
  computed: {},
  methods: {
    handleReset() {
      this.form.resetFields();
    },
    select(value, option) {
      // console.log(value,option);
      // this.editValue = value;
    },
    dropdownVisibleChange(open) {
      // console.log(open);
    },
    handleChange(value, option, index) {
      console.log(`selected ${value}`);
    },
    showModal(text) {
      this.visible = true;
      this.editId = text.id;
      this.editInit(text);
    },
    handleOk(e) {
      this.visible = false;
      var values = this.form.getFieldsValue();
      this.listEdit(values.classifyName);
      // console.log(this.formatter(values.superiorClassify, this.selectdata));
    },
    handleCancel(e) {
      console.log("点击取消了");
      this.visible = false;
    },

    // 绑定设备数弹框
    numberModal(text, record) {
      this.numberVisible = true;
      this.goodsTemplateId = record.id;
      this.findDevCodeListByGoodsTemplateId();
      this.numberTitle = record.name + "-绑定设备";
      // this.editId = text.id;
      // this.editInit(text);
    },
    numberOk(e) {
      this.numberVisible = false;
      // var values = this.form.getFieldsValue();
      // this.listEdit(values.classifyName);
      // console.log(this.formatter(values.superiorClassify, this.selectdata));
    },
    numberCancel(e) {
      this.numberVisible = false;
    },

    // 查看模板商品弹框
    goodsModal(text, record) {
      this.goodsVisible = true;
      this.findGoodsTemplateDetailList(record.id);
      this.goodsTitle = record.name + "-商品列表";
    },
    goodsOk(e) {
      this.goodsVisible = false;
      // var values = this.form.getFieldsValue();
      // this.listEdit(values.classifyName);
      // console.log(this.formatter(values.superiorClassify, this.selectdata));
    },
    goodsCancel(e) {
      console.log("点击取消了");
      this.goodsVisible = false;
    },

    // 复制确认框
    copyConfirm(text, record) {
      var that = this;
      this.copyId = record.id;
      // this.copyName = record.name;
      this.$confirm({
        title: "复制模板",
        content: `是否要复制模板：${record.name}？`,
        okText: "确定",
        cancelText: "取消",
        iconType: "question-circle",
        onOk() {
          that.listCopy(that.copyId);
          console.log("点击确定了");
        },
        onCancel() {
          console.log("点击取消了");
        }
      });
    },

    // 删除确认框
    delConfirm(text, record) {
      var that = this;
      this.delId = record.id;
      this.deviceNumber = record.deviceNumber;
      this.$confirm({
        title: "删除模板",
        content: `您确定要删除模板：${record.name} 吗？`,
        okText: "确定",
        cancelText: "取消",
        iconType: "question-circle",
        onOk() {
          that.listDelete(that.delId);
        },
        onCancel() {}
      });
    },

    // 有设备不能删除
    deviceNumberConfirm(text, record) {
      this.$message.warning("模板已绑定设备,解绑后才可以删除");
    },

    handleTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination };
      pager.current = pagination.current;
      pager.pageSize = pagination.pageSize;
      pager.total = pagination.total;
      this.pagination = pager;
      this.handleReset();
      this.findPageListByCondition();
    },

    // 列表初始化
    listInit() {
      this.axios
        .post(this.baseUrl + "/goodsTemplate/listInit", {
          loginToken: this.$store.state.loginToken
        })
        .then(response => {
          // console.log(response);
        })
    },

    // 查询商品模板列表
    findPageListByCondition() {
      var values = this.form.getFieldsValue();
      this.axios
        .post(this.baseUrl + "/goodsTemplate/findPageListByCondition", {
          loginToken: this.$store.state.loginToken,
          pageNum: this.pagination.current,
          pageSize: this.pagination.pageSize,
          name: values.templateName,
          templateCode: values.goodsNumber
        })
        .then(response => {
          // console.log(response);
          this.data = response.data.data.list;
          this.pagination.total = response.data.data.total;
          this.pagination.pageSize = response.data.data.pageSize;
          this.pagination.current = response.data.data.pageNum;
        })
    },

    // 查询模板下的设备编号
    findDevCodeListByGoodsTemplateId() {
      this.axios
        .post(
          this.baseUrl + "/goodsTemplate/findDevCodeListByGoodsTemplateId",
          {
            loginToken: this.$store.state.loginToken,
            goodsTemplateId: this.goodsTemplateId
          }
        )
        .then(response => {
          console.log(response);
          this.dataNumber = response.data.data;
        });
    },

    // 查询商品模板明细列表
    findGoodsTemplateDetailList(goodsTemplateId) {
      this.axios
        .post(this.baseUrl + "/goodsTemplate/findGoodsTemplateDetailList", {
          loginToken: this.$store.state.loginToken,
          goodsTemplateId: goodsTemplateId
        })
        .then(response => {
          // console.log(response);
          this.dataGoods = response.data.data;
        })
    },

    editInfo(text, record) {
      var goodsTemplateId = record.id;
      this.$store.commit("goodsTemplateId", goodsTemplateId);
      this.$router.push({
        path: "/home/goodsadmin/templateadmin/templateedit"
      });
    },

    // 导出点位
    listExport() {
      var values = this.form.getFieldsValue();
      this.axios
        .post(
          this.baseUrl + "/pos/export",
          {
            loginToken: this.$store.state.loginToken,
            name: values.templateName,
            templateCode: values.goodsNumber
          },
          { responseType: "arraybuffer" }
        )
        .then(response => {
          console.log(response);
          if (response.status == "200") {
            const aLink = document.createElement("a");
            let blob = new Blob([response.data], {
              type: "application/vnd.ms-excel"
            });
            aLink.href = URL.createObjectURL(blob);
            aLink.download = "模板管理表";
            aLink.click();
            document.body.appendChild(aLink);
          }
        })
    },

    // 删除商品模板
    listDelete(goodsTemplateId) {
      this.axios
        .post(this.baseUrl + "/goodsTemplate/del", {
          loginToken: this.$store.state.loginToken,
          goodsTemplateId: goodsTemplateId
        })
        .then(response => {
          console.log(response);
          if (response.data.code == 0) {
            this.findPageListByCondition();
            this.$message.success("删除成功");
          }
        })
        .catch(error => {
          console.log(error);
        });
    },

    // 复制商品模板
    listCopy(goodsTemplateId) {
      this.axios
        .post(this.baseUrl + "/goodsTemplate/copy", {
          loginToken: this.$store.state.loginToken,
          goodsTemplateId: goodsTemplateId
        })
        .then(response => {
          console.log(response);
          if (response.data.code == 0) {
            this.findPageListByCondition();
            this.$message.success("复制成功");
          }
        })
        .catch(error => {
          console.log(error);
        });
    }
  },
  created() {
    this.listInit();
    this.findPageListByCondition();
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.TemplateAdmin {
  width: 100%;
}
</style>
